package com.dm.cloud.utils.sql;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.dm.cloud.annotions.PopRequired;
import com.dm.cloud.utils.pager.PageVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Field;

public class SqlUtils {

    /**
     * 判断字段是否需要必填 缺少数据返回错误
     */
    public static <T> void valid(T entity) {

        Class cls = entity.getClass();

        Field[] fields = cls.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            PopRequired fieldNullable = AnnotationUtils.findAnnotation(f, PopRequired.class);
            //字段上没有该注解 返回非null属性
            if(fieldNullable != null){
                //字段上有该注解 则校验字段有没有值
                f.setAccessible(true);
                //判断是否为NULL
                try {
                    if (ObjectUtils.isNull(f.get(entity))) {
                        throw new RuntimeException(fieldNullable.msg());
                    }
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("字段非空校验失败");
                }
            }
        }
    }


    /**
     * 处理查询排序
     * @param wrapper
     * @param pageVo
     */
    public static void order(QueryWrapper wrapper , PageVo pageVo){
        //有排序要求
        if(StringUtils.isNotBlank(pageVo.getOrder()) && StringUtils.isNotBlank(pageVo.getField())){
            //获取需要排序的字段
            String orderField = pageVo.getField();
            //驼峰转下划线
            orderField = humpToUnderline(orderField);

            if("ascend".equals(pageVo.getOrder())){
                wrapper.orderByAsc(orderField);
            }else{
                wrapper.orderByDesc(orderField);
            }
        }
    }

    /**
     * 驼峰转下划线
     * @param origin
     * @return
     */
    private static String humpToUnderline(String origin){
        String result = "";

        for(int i = 0 ; i<origin.length();i++){
            //大写转下划线
            if(Character.isUpperCase(origin.charAt(i))){
                result += "_"+StringUtils.lowerCase(String.valueOf(origin.charAt(i)));
            }else{
                result += origin.charAt(i);
            }
        }
        return result;
    }
}
